package com.ziyucoding.springboot.labs.lab3.rocketmqdemo.producer;

import com.ziyucoding.springboot.labs.lab3.rocketmqdemo.message.Demo1Message;
import com.ziyucoding.springboot.labs.lab3.rocketmqdemo.message.Demo2Message;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 示例2的生产者（用于批量发送消息）
 *
 * @author ziyucoding
 * @date 2022-10-20
 **/
@Component
public class Demo2Producer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 批量同步发送消息
     *
     * @param ids
     * @return org.apache.rocketmq.client.producer.SendResult
     **/
    public SendResult sendBatch(Collection<Integer> ids) {
        // 创建消息
        // Message 必须是 Spring Messaging 定义的 Message 消息
        List<Message> messageList = new ArrayList<>(ids.size());
        for (Integer id : ids) {
            Demo2Message message = new Demo2Message(id);
            // 构建 Spring Messaging 定义的 Message 消息
            messageList.add(MessageBuilder.withPayload(message).build());
        }
        // 同步发送消息
        SendResult result = rocketMQTemplate.syncSend(Demo2Message.TOPIC, messageList, 30 * 1000L);
        return result;
    }
}
